<?php

namespace app\admin\model\manufacture;

use think\Model;

class Plan extends Model
{
    // 表名
    protected $name = 'manufacture_plan';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 追加属性
    protected $append = [
        'status_text',
        'priority_text'
    ];
    
    // 计划状态
    public function getStatusList()
    {
        return [
            '0' => __('草稿'),
            '1' => __('已发布'),
            '2' => __('执行中'),
            '3' => __('已完成'),
            '4' => __('已取消')
        ];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    
    // 优先级
    public function getPriorityList()
    {
        return [
            '1' => __('低'),
            '2' => __('中'),
            '3' => __('高'),
            '4' => __('紧急')
        ];
    }

    public function getPriorityTextAttr($value, $data)
    {
        $value = $value ? $value : $data['priority'];
        $list = $this->getPriorityList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 关联订单
    public function order()
    {
        return $this->belongsTo('app\admin\model\scanwork\Order', 'order_id', 'id');
    }

    // 关联计划明细
    public function planDetails()
    {
        return $this->hasMany('app\admin\model\manufacture\PlanDetail', 'plan_id', 'id');
    }

    // 获取进度百分比
    public function getProgressAttr($value, $data)
    {
        if ($data['planned_quantity'] == 0) {
            return 0;
        }
        return round(($data['completed_quantity'] / $data['planned_quantity']) * 100, 2);
    }

    // 获取剩余数量
    public function getRemainingQuantityAttr($value, $data)
    {
        return $data['planned_quantity'] - $data['completed_quantity'];
    }

    // 获取计划天数
    public function getPlanDaysAttr($value, $data)
    {
        if (!$data['start_date'] || !$data['end_date']) {
            return 0;
        }
        $start = strtotime($data['start_date']);
        $end = strtotime($data['end_date']);
        return ceil(($end - $start) / 86400) + 1;
    }

    // 获取已执行天数
    public function getExecutedDaysAttr($value, $data)
    {
        if (!$data['start_date']) {
            return 0;
        }
        $start = strtotime($data['start_date']);
        $now = time();
        return ceil(($now - $start) / 86400) + 1;
    }
}
